<?php

include_once("constants.php");
require_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR ."Model".DIRECTORY_SEPARATOR."phpmailer".DIRECTORY_SEPARATOR."class.phpmailer.php");

class core{

	public static function sanitize($input) {
	    if (is_array($input)) 
	    {
	        foreach($input as $var=>$val) {
	            $output[$var] = sanitize($val); 
	        }
	    }
	    else 
	    {
	        if (get_magic_quotes_gpc()) {
	            $input = stripslashes($input);
	        }
	        $output = mysql_real_escape_string($input);
	        $output = htmlentities($input);
	    }
	    return $output;
	}


	/**
	function to load the file supplied in the format of
	Usage : Directory.filename
			Directory.subdirectory.filename
			Directory.subdirectory.....filename
	Directory/filename
	or
	Directory/subdirectory/filename
	or
	Directory/subdirectory/...../filename
	*/
	public static function getResource($resource)
	{
		$array = explode('.',$resource);
		$size = sizeof($array)-1;//2
		$filePath = null;
		for($i=0;$i<=$size;$i++)
		{
			$filePath .= $array[$i];
			if($i < ($size))
			{
				$filePath .= DIRECTORY_SEPARATOR;
			}
		}
		include_once($filePath.".php");
	}

	public static function isLoggedIn()
	{
		if (session_id()==''/*session_status() == PHP_SESSION_NONE*/) {
    		session_start();
		}
		if(isset($_SESSION['personId']))
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	public static function redirect($url)
	{
		header("Location: $url");
	}

	public static function cVal($constantName)
	{
		return constant($constantName);
	}

	public static function searchEvent($eventName)
	{
		Core::getResource("Model.Database");
		$dbConn = new dbConn();
		$cnd = "name LIKE '$eventName%'";
		$sql = "SELECT eventId,name FROM event WHERE ".$cnd;
		$res = $dbConn->query($sql);
		$array = array();
		if($dbConn->num_rows($res) >= 1)
		{
			while($data = $dbConn->fetch_array($res))
			{
				$array[] = $data;
			}
			return ($array);
		}
		else
		{
			return null;
		}
	}
    
    public static function filterApplicants($role,$filter)
    {
        Core::getResource("Model.Database");
		$dbConn = new dbConn();
		$cnd = "LOWER(person.skills) LIKE LOWER('%$filter%')";
		$sql = "SELECT person.personId,person.firstName,person.lastName "
            . "FROM person JOIN applied ON person.personId=applied.person "
            . "WHERE applied.role=$role AND $cnd";
		$res = $dbConn->query($sql);
		$array = array();
		if($dbConn->num_rows($res) >= 1)
		{
			while($data = $dbConn->fetch_array($res))
			{
				$array[] = $data;
			}
			return ($array);
		}
		else
		{
			return null;
		}
    }

	public static function getUserDetailsArray($personId)
	{
		Core::getResource("Model.Database");
		$db = new dbConn();
		$query = "SELECT firstName,lastName,accountType,email,skills,universityId,gender,contactNumber,address,driversLicence,availability,dateCreated,activated from person WHERE personId=$personId";
		$res = $db->query($query); 
		$data = $db->fetch_array($res);
		return $data;
	}
    
    public static function getAppliedByPerson($id) 
    {
        Core::getResource("Model.Database");
        $conn = new dbConn();
		$query = "SELECT applied.role,role.title FROM role JOIN applied ON applied.role=role.roleId WHERE applied.person=$id";
		$res = $conn->query($query);
		if($conn->num_rows($res) >= 1)
		{
			$array = array();
			while($row = $conn->fetch_array($res))
			{
				$array[] = $row;
			}
			return ($array);
		}
		else
		{
			return null;
		}
    }
    public static function getApplied($personId,$roleId)
    {
        Core::getResource("Model.Database");
		$db = new dbConn();
        $query = "SELECT hoursWorked,accepted,attended FROM applied WHERE person=$personId AND role=$roleId";
		$res = $db->query($query); 
		$data = $db->fetch_array($res);
		return $data;
    }

	public static function getEventDetailsArray($eventId)
	{
		Core::getResource("Model.Database");
		$db = new dbConn();
		$query = "SELECT * FROM event WHERE eventId=$eventId";
		$res = $db->query($query);
		$data = $db->fetch_array($res);
		return $data;
	}

	public static function getEventFromDate($startDate)
	{
		Core::getResource("Model.Database");
		$db = new dbConn();
		$query = "SELECT * FROM event WHERE startDate=$startDate";
		$res = $db->query($query);
		$data = $db->fetch_array($res);
		if(!is_null($data))
		{
			return $data;
		}
		else
		{
			return null;
		}
	}

	public static function getRoleDetailsArray($roleId)
	{
		Core::getResource("Model.Database");
		$db = new dbConn();
		$query = "SELECT * FROM role WHERE roleId=$roleId";
		$res = $db->query($query);
		return $db->fetch_array($res);
	}

	public static function getRolePositionArray($roleId)
	{
		Core::getResource("Model.Database");
		$db = new dbConn();
		$query = "SELECT positions,payRate FROM role WHERE roleId=$roleId";
		$res = $db->query($query);
		return $db->fetch_array($res);
	}

	public static function getUniDetailsArray($personId)
	{
		Core::getResource("Model.Database");
		$db = new dbConn();
		$query = $db->query("SELECT * FROM person WHERE personId=$personId");
		return $db->fetch_array($query);
	}

	public static function getEventManagers($eventId)
	{
		Core::getResource("Model.Database");
		$db = new dbConn();
		$res = $db->query("SELECT person FROM manages WHERE event=$eventId LIMIT 5");
		if($db->num_rows($res) > 0)
		{
			$array = array();
			while($row = $db->fetch_array($res))
			{
				$array[] = $row;
			}
			return $array;
		}
		else
		{
			return null;
		}
		
	}

	public static function getOtherDetailsArray($otherId)
	{
		Core::getResource("Model.Database");
		$db = new dbConn();
		$res = $db->query("SELECT * FROM person WHERE personId=$otherId");
		return $db->fetch_array($res);
	}

	public static function getMgrsTotal($eventId)
	{
		Core::getResource("Model.Database");
		$db = new dbConn();
		$res = $db->query("SELECT * FROM manages WHERE event=$eventId");
		return $db->num_rows($res);
	}

	public static function getActvityDetailsArray($id)
	{
		Core::getResource("Model.Database");
		$db = new dbConn();
		$res = $db->query("SELECT * FROM activity WHERE activityId=$id");
		return $db->fetch_array($res);
	}

	public static function addToMailingList($email)
	{
		Core::getResource("Model.Database");
		$db = new dbConn();
		$res = false;
		if(!self::inMailingList($email))
		{
			$res = $db->insert("INSERT INTO mailing_list (email) VALUES ('$email')");
			$message = "You have been added to our mailing list! <br/> Thank you for your subscription! <br/><br/> UTS:V Admin";
			self::sendMail($email,"Thank You for Subscribing!",$message);
			return true;
		}
		else
		{
			return false;
		}
	}

	public static function inMailingList($email)
	{
		Core::getResource("Model.Database");
		$db = new dbConn();
		if($db->num_rows($db->query("SELECT * FROM mailing_list WHERE email='$email'")) > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
    public static function resendMail($page)
    {
        $message = "Your Activation Key is : <h2>";
        $message .= $page->getActivationKey();
        $message .= "</h2><br/>";
        $message .= "Thank You for registering!";
        $message .= "<br/>We Welcome you to UTS Volunteering Portal, ";
        $message .= $page->personFName();
        $message .= "<br/><br/>Login in to the UTS:V website and enter this activation key";
        $message .= "<br/><br/>";
        $message .= "UTS:V Admin";
        Core::sendMail($page->personEmail(),"UTS:V Account Activation",$message);
    }
	public static function sendMail($to,$subject,$message)
	{
		$mail = new PHPMailer();
		$mail->IsSMTP();
		$mail->SMTPDebug = 1;
		$mail->SMTPAuth = true;
		$mail->SMTPSecure = 'ssl';
		$mail->Host = "smtp.gmail.com";
		$mail->Port = 465;
		$mail->IsHtml(true);
		$mail->Username = "utsdpmailer@gmail.com";
		$mail->Password = "ma!ler123";
		$mail->From = "utsdpmailer@gmail.com";
		$mail->FromName = "UTS:V Admin";
		$mail->Subject = $subject;
		$mail->Body = $message;
		$mail->AddAddress($to);
		if(!$mail->send())
		{
			echo "Mailer Error : ".$mail->ErrorInfo;
		}
	}

	public static function tryActivating($personId,$activationKey)
	{
		$person = new Person($personId);
		if($person->activationKey == $activationKey)
		{
			$person->setActivated(1);
			return true;
		}else
		{
			return false;
		}
	}
}




/**
	AUTOLOADER FUNCTION TO LOAD CLASS FILES AUTOMATICALLY WHEN AN INSTANCE/OBJECT OF A CLASS IS CREATED
 */

function base_autoloader($name)
{
	if(file_exists(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR ."model".DIRECTORY_SEPARATOR.$name.".php"))
	{
		require_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR ."model".DIRECTORY_SEPARATOR.$name.".php");
	}
	else if(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR ."controller".DIRECTORY_SEPARATOR.$name.".php")
	{
		require_once(dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR ."controller".DIRECTORY_SEPARATOR.$name.".php");
	}
	else
	{
		die("Could not load file $name");
	}
}

spl_autoload_register('base_autoloader');

?>